package cn.hengzhu.main_manager.web.xcx;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import cn.hengzhu.main_manager.repository.dao.AccessRecordMapper;
import cn.hengzhu.main_manager.repository.dao.CustomersAmountMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseBoxMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseMapper;
import cn.hengzhu.main_manager.repository.dao.PayOrderMapper;
import cn.hengzhu.main_manager.repository.dao.SysConstMapper;
import cn.hengzhu.main_manager.repository.domain.AccessRecord;
import cn.hengzhu.main_manager.repository.domain.CustomersAmount;
import cn.hengzhu.main_manager.repository.domain.CustomersAmountExample;
import cn.hengzhu.main_manager.repository.domain.ManageCase;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBox;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBoxExample;
import cn.hengzhu.main_manager.repository.domain.ManageCaseExample;
import cn.hengzhu.main_manager.repository.domain.PayOrder;
import cn.hengzhu.main_manager.repository.domain.PayOrderExample;
import cn.hengzhu.main_manager.repository.domain.SysConst;
import cn.hengzhu.main_manager.repository.domain.SysConstExample;
import cn.hengzhu.main_manager.repository.vo.BoxUseRecordVO;
import cn.hengzhu.main_manager.repository.vo.CaseByDoorVO;
import cn.hengzhu.main_manager.repository.vo.XcxRecordVO;
import cn.hengzhu.main_manager.service.CustomersAmountService;
import cn.hengzhu.main_manager.service.ManageCaseBoxService;
import cn.hengzhu.main_manager.utils.ConnectionUtils;
import cn.hengzhu.main_manager.utils.DateTimeHelper;
import cn.hengzhu.main_manager.utils.DbByteToString;
import cn.hengzhu.main_manager.utils.DictionaryUtils;
import cn.hengzhu.main_manager.utils.TimeFormatUtil;
import cn.hengzhu.main_manager.utils.config.AppConfig;
import cn.hengzhu.main_manager.utils.config.CaseUseTypeConst;
import cn.hengzhu.main_manager.utils.config.xcx.AliConfig;

/**
 * @author 刘成
 * @since 2018年10月12日
 * 
 *        支付宝小程序共享床
 */
@Controller
@RequestMapping("/alixcx")
public class ALiXcxController {

	private Logger log = Logger.getLogger(ALiXcxController.class);
	@Autowired
	private CustomersAmountMapper customersAmountMapper;
	@Autowired
	private ManageCaseBoxMapper manageCaseBoxMapper;
	@Autowired
	private ManageCaseBoxService manageCaseBoxService;
	@Autowired
	private PayOrderMapper payOrderMapper;
	@Autowired
	private SysConstMapper sysConstMapper;
	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private AccessRecordMapper accessRecordMapper;
	@Autowired
	private CustomersAmountService customersAmountService;

	/**
	 * @author 刘成
	 * @since 2018年9月13日
	 * @param code
	 * @return
	 * @throws Exception
	 *             获取支付宝的openid（userid）
	 */
	@RequestMapping("/getOpenId")
	@ResponseBody
	public Map<String, String> getOpenId(String code) throws Exception {
		Map<String, String> map = new HashMap<>();
		AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID, AliConfig.PRIVATE_KEY,
				"json", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
		request.setGrantType("authorization_code");
		request.setCode(code);
		AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
		String userId = response.getUserId();

		// 查询是否有账号，，，没有就新建，，，有就不管
		CustomersAmountExample example = new CustomersAmountExample();
		example.createCriteria().andOpenIdEqualTo(userId).andSourceEqualTo(Byte.valueOf("3"));
		List<CustomersAmount> selectByExample = customersAmountMapper.selectByExample(example);
		if (selectByExample.isEmpty()) {
			CustomersAmount customersAmount = new CustomersAmount();
			customersAmount.setCreateTime(new Date());
			customersAmount.setOpenId(userId);
			customersAmount.setSource((byte) 3);
			customersAmountMapper.insertSelective(customersAmount);
		}
		map.put("userId", userId);
		return map;
	}

	/**
	 * @author 刘成
	 * @since 2018年9月13日
	 * @param caseNo
	 * @param openId
	 * @return
	 * @throws Exception
	 *             开箱
	 */
	@RequestMapping("/openbox")
	@ResponseBody
	public Map<String, String> openbox(String caseNo, String openId) throws Exception {
		Byte useType = CaseUseTypeConst.HOSPITAL_BED_CASE;// 用途为医用床
		Map<String, String> map = new HashMap<>();
		// 开柜前
		// 1.查询是否缴纳押金
		CustomersAmountExample amountExample = new CustomersAmountExample();
		// SOURCE字段 来源（2，微信小程序   3.支付宝小程序''）
		amountExample.createCriteria().andOpenIdEqualTo(openId).andSourceEqualTo((byte) 3); // from customers_amount where openId = ? and  SOURCE = 3
		List<CustomersAmount> selectByExample = customersAmountMapper.selectByExample(amountExample);

		if (!selectByExample.isEmpty()) {// 先判断有无账户
			CustomersAmount customersAmount = selectByExample.get(0);
			Byte isPay = customersAmount.getIsPay();
			BigDecimal totalAmount = customersAmount.getTotalAmount();
			double doubleValue = totalAmount.doubleValue();
			if (Byte.valueOf("0").equals(isPay)) {// 未缴纳押金
				map.put("jumpPage", "1");
				map.put("openboxMessage", "请先缴纳押金再使用此柜，点击确定进行押金缴纳");
				return map;
			} else if (Byte.valueOf("2").equals(isPay)) {
				map.put("jumpPage", "0");
				map.put("openboxMessage", "您已申请退回押金，暂时不能使用此类储物柜");
				return map;
			} else {// 剩下的为已缴纳押金或者押金退回失败的
					// 2.查询是否欠费
				if (doubleValue >= 0) {// 正常开启
					///////////////////////////////////////////////////////////////////
					Date date = new Date();

					// 查询是否已经在使用中
					int count = manageCaseBoxMapper.selectByOpenIdAndUseType(openId, useType);
					if (count > 0) {
						map.put("jumpPage", "0");
						map.put("openboxMessage", "您已经使用了此类储物柜，不能再开启此类储物柜");
						return map;
					} else {

						ManageCaseBoxExample caseBoxExample = new ManageCaseBoxExample();
						caseBoxExample.createCriteria().andUseStatusEqualTo((byte) 0).andIsDelEqualTo((byte) 0)
								.andSwitchStatusEqualTo((byte) 1).andCaseNoEqualTo(caseNo);
						List<ManageCaseBox> list = manageCaseBoxMapper.selectByExample(caseBoxExample);

						if (!list.isEmpty()) {
							ManageCaseBox manageCaseBox = list.get(0);
							Integer doorNum = manageCaseBox.getDoorNum();
							Connection connection = ConnectionUtils.getConnection();
							Channel channel = connection.createChannel();
							Map<String, Object> sendMap = new HashMap<>();
							sendMap.put("door", doorNum);
							sendMap.put("timestamp", date.getTime());
							ObjectMapper mapper = new ObjectMapper();
							Map<String, Object> args = new HashMap<String, Object>();
							args.put("x-message-ttl", 40000);
							channel.queueDeclare(caseNo, true, false, false, args);
							String writeValueAsString = mapper.writeValueAsString(sendMap);
							try {
								// 3.缴纳了押金又没有欠费，执行开柜操作
								manageCaseBoxService.openBoxByAliXcx(manageCaseBox, openId);
								channel.basicPublish("", caseNo, null, writeValueAsString.getBytes());
								channel.close();
								connection.close();
								map.put("jumpPage", "200");
								map.put("openboxMessage", "开启成功，请放心使用");
								return map;

							} catch (Exception e) {
								map.put("jumpPage", "0");
								map.put("openboxMessage", "开启失败，请重试");
								return map;
							}
						} else {
							map.put("jumpPage", "0");
							map.put("openboxMessage", "没有空余的箱子了");
							return map;
						}
					}
				} else {
					map.put("jumpPage", "2");
					map.put("openboxMessage", "您已欠费，请充值后再使用");
					return map;
				}
			}
		} else {
			CustomersAmount customersAmount = new CustomersAmount();
			customersAmount.setCreateTime(new Date());
			customersAmount.setOpenId(openId);
			customersAmount.setSource((byte) 3);
			customersAmountMapper.insertSelective(customersAmount);
			map.put("jumpPage", "1");
			map.put("openboxMessage", "请先缴纳押金再使用此柜，点击确定进行押金缴纳");
			return map;

		}
	}

	/**
	 * @author 刘成
	 * @since 2018年9月13日
	 * @param caseNo
	 * @param openId
	 * @return
	 * @throws Exception
	 *             支付宝 -----充值-------统一下单接口
	 */
	@RequestMapping("/tradeCreate")
	@ResponseBody
	public Map<String, String> tradeCreate(String amount, String userId) throws Exception {
		Map<String, String> returnMap = new HashMap<>();
		String nonce_str = DictionaryUtils.getRandomStr();
		String out_trade_no = "cz_ali" + new Date().getTime() + nonce_str.substring(0, 2);// 商户订单号,64个字符以内、

		double total_amount = Double.valueOf(amount);
		// 订单总金额，单位为元，精确到小数点后两位
		String subject = "充值";

		Map<String, Object> map = new HashMap<>();
		map.put("out_trade_no", out_trade_no);
		map.put("total_amount", total_amount);
		map.put("subject", subject);
		map.put("buyer_id", userId);
		String jsonString = JSONObject.toJSONString(map);
		AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID, AliConfig.PRIVATE_KEY,
				"JSON", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();

		request.setNotifyUrl(AliConfig.DOMAIN_URL + "/alixcx/rechargeFinishNotify");
		request.setBizContent(jsonString);
		AlipayTradeCreateResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			String tradeNo = response.getTradeNo();
			// 将订单号插入数据库
			PayOrder record = new PayOrder();
			record.setCreartTime(new Date());
			record.setIsPay((byte) 0);
			record.setOpenId(userId);
			record.setOutTradeNo(out_trade_no);
			Double valueOf = Double.valueOf(amount);
			Double money = valueOf * 100;
			record.setTotalFee(money.intValue());
			record.setTransactionId(tradeNo);
			payOrderMapper.insertSelective(record);
			returnMap.put("code", "200");
			returnMap.put("tradeNo", tradeNo);
		} else {
			returnMap.put("code", "400");
		}
		return returnMap;
	}

	/**
	 * @author 刘成
	 * @since 2018年9月14日
	 * @param tradeNo
	 * @return
	 * @throws Exception
	 *             充值----支付完成接口
	 */
	@RequestMapping("/payFinish")
	@ResponseBody
	public Map<String, String> payFinish(String tradeNo) throws Exception {
		// PayOrderExample example = new PayOrderExample();
		// example.createCriteria().andTransactionIdEqualTo(tradeNo).andIsPayEqualTo((byte)
		// 0);
		// List<PayOrder> selectByExample =
		// payOrderMapper.selectByExample(example);
		// if (!selectByExample.isEmpty()) {
		// // 1.有这个订单号而且是没有支付的
		// // 2.修改订单状态为支付完成
		// PayOrder payOrder = selectByExample.get(0);
		// try {
		// manageCaseBoxService.payFinishByAli(payOrder);
		// } catch (Exception e) {
		// map.put("finishMessage", "服务器开小差了，请联系管理员处理");
		// }
		// }
		Map<String, String> map = new HashMap<>();
		map.put("finishMessage", "支付成功");
		return map;

	}

	/**
	 * @author liuCheng
	 * @since 2018年11月8日 上午11:41:44
	 * @param tradeNo
	 * @return
	 * @throws Exception
	 *             充值完成后的异步接口
	 */
	@RequestMapping("/rechargeFinishNotify")
	@ResponseBody
	public String rechargeFinishNotify(HttpServletRequest request) throws Exception {
		String trade_no = request.getParameter("trade_no");
		String trade_status = request.getParameter("trade_status");
		String out_trade_no = request.getParameter("out_trade_no");
		String buyer_id = request.getParameter("buyer_id");
		if (StringUtils.isNotBlank("trade_status") && trade_status.equals("TRADE_SUCCESS")) {
			// 查询订单
			PayOrderExample example = new PayOrderExample();
			example.createCriteria().andIsPayEqualTo((byte) 0).andOpenIdEqualTo(buyer_id)
					.andTransactionIdEqualTo(trade_no).andOutTradeNoEqualTo(out_trade_no);
			List<PayOrder> payOrderList = payOrderMapper.selectByExample(example);
			if (!payOrderList.isEmpty()) {
				PayOrder payOrder = payOrderList.get(0);
				try {
					customersAmountService.rechargeFinishByAliXCX(payOrder);
					return "success";
				} catch (Exception e) {
					return "";
				}

			} else {
				return "";
			}

		} else {
			return "";
		}

	}

	/**
	 * @author 刘成
	 * @since 2018年9月18日
	 * @param openId
	 * @return 用户基本信息
	 */
	@RequestMapping("/userInfo")
	@ResponseBody
	public Map<String, Object> userInfo(String openId) {
		// 查询所需缴纳的押金数额
		SysConstExample payexample = new SysConstExample();
		payexample.createCriteria().andNameEqualTo(AppConfig.ASSURE_AMOUNT);
		List<SysConst> selectByExample2 = sysConstMapper.selectByExample(payexample);
		// 需缴纳的押金数
		String payNum = selectByExample2.get(0).getValue();
		Double valueOf = Double.valueOf(payNum);
		Double ass = valueOf / 100;

		Map<String, Object> map = new HashMap<>();
		String assureAmount = ass.toString();
		String totalAmount = "0.0";
		Byte isPay = 0;
		Integer integral = 0;
		String useTime = "00:00:00";
		// 根据openID查询用户的账户信息并返回查询结果
		CustomersAmountExample example = new CustomersAmountExample();
		example.createCriteria().andOpenIdEqualTo(openId).andSourceEqualTo(Byte.valueOf("3"));
		List<CustomersAmount> selectByExample = customersAmountMapper.selectByExample(example);
		if (!selectByExample.isEmpty()) {// 有
			CustomersAmount customersAmount = selectByExample.get(0);
			// 是否缴纳押金
			isPay = customersAmount.getIsPay();
			// 所交押金数额
			payNum = customersAmount.getAssureAmount().toString();
			// 账户积分
			integral = customersAmount.getIntegral();
			// 账户余额
			BigDecimal total = customersAmount.getTotalAmount();
			totalAmount = total.toString();
			if (Byte.valueOf("1").equals(isPay)) {// 缴纳
				BigDecimal assure = customersAmount.getAssureAmount();
				assureAmount = assure.toString();
			}

			ManageCaseBoxExample caseNoExample = new ManageCaseBoxExample();
			caseNoExample.createCriteria().andUserIdEqualTo(openId).andUseStatusEqualTo((byte) 1)
					.andIsDelEqualTo((byte) 0);
			List<ManageCaseBox> list = manageCaseBoxMapper.selectByExample(caseNoExample);

			Map<String, ManageCaseBox> collect = list.stream()
					.collect(Collectors.toMap(ManageCaseBox::getCaseNo, a -> a));
			List<String> caseNoList = list.stream()
					.collect(Collectors.mapping(ManageCaseBox::getCaseNo, Collectors.toList()));
			if (caseNoList != null && !caseNoList.isEmpty()) {

				ManageCaseExample caseExample = new ManageCaseExample();
				caseExample.createCriteria().andCaseNoIn(caseNoList).andUseTypeEqualTo((byte) 2);
				List<ManageCase> selectByExample3 = manageCaseMapper.selectByExample(caseExample);

				if (!selectByExample3.isEmpty()) {
					ManageCase manageCase = selectByExample3.get(0);
					String caseNo = manageCase.getCaseNo();
					ManageCaseBox manageCaseBox = collect.get(caseNo);
					Date saveTime = manageCaseBox.getSaveTime();
					Date date = new Date();
					long time = date.getTime() - saveTime.getTime();
					useTime = TimeFormatUtil.getMinutesTime(time);
				}
			}
		} else {// 没有
				// 第一次使用，，，插入数据
			CustomersAmount customersAmount = new CustomersAmount();
			customersAmount.setCreateTime(new Date());
			customersAmount.setOpenId(openId);
			customersAmount.setSource((byte) 3);
			customersAmountMapper.insertSelective(customersAmount);
		}
		map.put("assureAmount", assureAmount);
		map.put("totalAmount", totalAmount);
		map.put("isPay", isPay);
		map.put("useTime", useTime);
		map.put("openId", openId);
		map.put("payNum", payNum);
		map.put("integral", integral);
		return map;
	}

	/**
	 * @author 刘成
	 * @throws Exception
	 * @since 2018年9月18日 支付宝退款接口
	 */
	@RequestMapping("/refund")
	@ResponseBody
	public Map<String, String> refund(String openId) throws Exception {
		log.info("支付宝申请退款。。。。。");
		Map<String, Object> paramMap = new HashMap<>();
		Map<String, String> returnMap = new HashMap<>();
		// 查询押金的订单号和押金金额
		CustomersAmountExample example = new CustomersAmountExample();
		example.createCriteria().andOpenIdEqualTo(openId).andSourceEqualTo((byte) 3);
		List<CustomersAmount> selectByExample = customersAmountMapper.selectByExample(example);
		if (!selectByExample.isEmpty()) {
			CustomersAmount customersAmount = selectByExample.get(0);
			Byte isPay = customersAmount.getIsPay();
			if (Byte.valueOf("1").equals(isPay)) {// 已经缴纳押金
				// 缴纳了押金还需要判断是否欠费
				BigDecimal totalAmount2 = customersAmount.getTotalAmount();
				double doubleValue = totalAmount2.doubleValue();
				if (doubleValue >= 0) {// 余额大于0
					// 余额大于0，查询是否正在使用中

					ManageCaseBoxExample caseBoxExample = new ManageCaseBoxExample();
					caseBoxExample.createCriteria().andUserIdEqualTo(openId).andIsDelEqualTo((byte) 0)
							.andUseStatusEqualTo((byte) 1);
					List<ManageCaseBox> list = manageCaseBoxMapper.selectByExample(caseBoxExample);

					if (!list.isEmpty()) {
						returnMap.put("jumpPage", "0");
						returnMap.put("refundMessage", "您有柜子处于使用状态不能进行退款操作，请谅解！！！");
					} else {
						String random = UUID.randomUUID().toString().replaceAll("-", "");
						String assureTransactionId = customersAmount.getAssureTransactionId();
						BigDecimal totalAmount = customersAmount.getAssureAmount();// 退还押金
						AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID,
								AliConfig.PRIVATE_KEY, "json", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
						AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
						paramMap.put("trade_no", assureTransactionId);
						paramMap.put("refund_amount", totalAmount);
						paramMap.put("out_request_no", random);
						paramMap.put("refund_reason", "退还押金");
						String jsonString = JSONObject.toJSONString(paramMap);
						log.info("支付宝退款：tradeNO:" + assureTransactionId + " refundAmount:" + totalAmount);
						request.setBizContent(jsonString);
						AlipayTradeRefundResponse response = alipayClient.execute(request);
						log.info(response.getBody());
						if (response.isSuccess()) {
							customersAmountService.backPayByAli(response, customersAmount);
							returnMap.put("jumpPage", "0");
							returnMap.put("refundMessage", "申请退款成功");
						} else {
							returnMap.put("jumpPage", "0");
							returnMap.put("refundMessage", "申请退款失败");
						}
					}

				} else {
					returnMap.put("jumpPage", "1");
					returnMap.put("refundMessage", "您已欠费请先充值后再进行操作");
				}
			} else {// 没有缴纳押金
				returnMap.put("jumpPage", "2");
				returnMap.put("refundMessage", "没有可退押金");
			}
		} else {
			returnMap.put("jumpPage", "0");
			returnMap.put("refundMessage", "系统错误，请稍后重试");
		}
		return returnMap;
	}


	/**
	 * @author 刘成
	 * @since 2018年9月19日
	 * @param openId
	 * @return 订单列表
	 */
	@RequestMapping("/myOrderList")
	@ResponseBody
	public List<XcxRecordVO> myOrderList(String openId) {
		List<XcxRecordVO> returnList = new ArrayList<>();

		List<AccessRecord> list = accessRecordMapper.getRecordListByOpenId(openId);
		List<Integer> boxIdList = list.stream().map(AccessRecord::getBoxId).distinct().collect(Collectors.toList());//获取此人员使用的所有boxId，已过滤重复
		
		if(boxIdList.isEmpty() || list.isEmpty()){
			return returnList;
		}
		//记录不为空是查询储物柜
		List<ManageCaseBox> selectInBoxId = manageCaseBoxMapper.selectInBoxId(boxIdList);
		Map<Integer, Integer> idAndDoorNumMap = selectInBoxId.stream().collect(Collectors.toMap(ManageCaseBox::getId,ManageCaseBox::getDoorNum));
		Map<Integer, String> idAndCaseNoMap = selectInBoxId.stream().collect(Collectors.toMap(ManageCaseBox::getId,ManageCaseBox::getCaseNo));
		List<String> caseNoList = selectInBoxId.stream().map(ManageCaseBox::getCaseNo).distinct().collect(Collectors.toList());
		//根据caseNo查询储物柜柜子
		List<ManageCase> selectInCaseNo = manageCaseMapper.selectInCaseNo(caseNoList);
		Map<String, List<ManageCase>> mcGroupBycaseNo = selectInCaseNo.stream().collect(Collectors.groupingBy(ManageCase::getCaseNo));
		
		list.stream().forEach(new Consumer<AccessRecord>() {
			@Override
			public void accept(AccessRecord a) {
				XcxRecordVO recordVO = new XcxRecordVO();
				Byte type = a.getType();
				BoxUseRecordVO accessRecordTypeToString = DbByteToString.accessRecordTypeToString(type);
				String useType = accessRecordTypeToString.getType();
				// 1.结算时间
				Date createTime = a.getCreateTime();
				String formatDateTimetoString = DateTimeHelper.formatDateTimetoString(createTime, "yyyy-MM-dd HH:mm");
				// 2.使用时长
				Long useTime = a.getUseTime();
				String minutesTime = TimeFormatUtil.getMinutesTime(useTime);
				// 3.使用费用
				BigDecimal charge = a.getCharge();
				recordVO.setCharge(charge.toString());
				recordVO.setUseType(useType);
				recordVO.setEndPayTime(formatDateTimetoString);
				recordVO.setUseTime(minutesTime);
				recordVO.setDoorNum(idAndDoorNumMap.get(a.getBoxId()));
				List<ManageCase> list2 = mcGroupBycaseNo.get(idAndCaseNoMap.get(a.getBoxId()));
				if(list2!=null&&!list2.isEmpty()){
					StringBuffer place = new StringBuffer(idAndCaseNoMap.get(a.getBoxId()));
					if(StringUtils.isNotBlank(list2.get(0).getPlace())){
						place.setLength(0);
						place.append(list2.get(0).getPlace());
					}
					if(StringUtils.isNotBlank(list2.get(0).getCaseNoBuy())){
						place.append(" "+list2.get(0).getCaseNoBuy()+"号柜");
					}
					recordVO.setPlace(String.valueOf(place));
				}
				returnList.add(recordVO);

			}
		});
		return returnList;
	}

	/**
	 * @author 刘成
	 * @since 2018年9月20日
	 * @throws AlipayApiException
	 *             转账
	 */
	@RequestMapping("/transfer")
	@ResponseBody
	// TODO 未完成的接口
	public void transfer() throws AlipayApiException {
		AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID, AliConfig.PRIVATE_KEY,
				"JSON", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		Map<String, String> map = new HashMap<>();
		map.put("out_biz_no", "sjidgbyuhsagbj");
		map.put("payee_type", "ALIPAY_LOGONID");
		map.put("payee_account", "2088802735026474");
		map.put("amount", "0.2");
		String jsonString = JSONObject.toJSONString(map);
		request.setBizContent(jsonString);
		AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
		System.out.println(response.getBody());
		if (response.isSuccess()) {
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}

	}

	/**
	 * @author 刘成
	 * @since 2018年9月20日
	 * @throws AlipayApiException
	 *             支付押金
	 */
	@RequestMapping("/cashPay")
	@ResponseBody
	public Map<String, String> cashPay(String userId) throws AlipayApiException {
		Map<String, String> returnMap = new HashMap<>();
		SysConstExample payexample = new SysConstExample();
		payexample.createCriteria().andNameEqualTo(AppConfig.ASSURE_AMOUNT);
		List<SysConst> selectByExample2 = sysConstMapper.selectByExample(payexample);
		// 1.查询需缴纳的押金数
		String totalFee = selectByExample2.get(0).getValue();
		// 2.生成订单号并返回
		String nonce_str = DictionaryUtils.getRandomStr();
		String out_trade_no = "yj_ali" + new Date().getTime() + nonce_str.substring(0, 2);// 商户订单号,64个字符以内、
		String subject = "押金";
		Map<String, Object> map = new HashMap<>();
		map.put("out_trade_no", out_trade_no);
		map.put("total_amount", Double.valueOf(totalFee) / 100);
		map.put("subject", subject);
		map.put("buyer_id", userId);
		String jsonString = JSONObject.toJSONString(map);
		AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID, AliConfig.PRIVATE_KEY,
				"JSON", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
		// TODO
		request.setNotifyUrl(AliConfig.DOMAIN_URL + "/alixcx/payCaseFinishByNotify");
		request.setBizContent(jsonString);
		AlipayTradeCreateResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			String tradeNo = response.getTradeNo();
			// 将订单号插入数据库
			PayOrder record = new PayOrder();
			record.setCreartTime(new Date());
			record.setIsPay((byte) 0);
			record.setOpenId(userId);
			record.setOutTradeNo(out_trade_no);
			Double valueOf = Double.valueOf(totalFee);
			record.setTotalFee(valueOf.intValue());
			record.setTransactionId(tradeNo);
			payOrderMapper.insertSelective(record);
			returnMap.put("code", "200");
			returnMap.put("tradeNo", tradeNo);
		} else {
			returnMap.put("code", "400");
		}
		return returnMap;
	}

	/**
	 * @author liuCheng
	 * @since 2018年11月8日 下午3:42:18
	 * @param tradeNo
	 * @param openId
	 * @return
	 * @throws Exception
	 *             押金支付完成后的逻辑处理（异步通知接口）
	 */
	@RequestMapping("/payCaseFinishByNotify")
	@ResponseBody
	public String payCaseFinishByNotify(HttpServletRequest request) throws Exception {
		String trade_no = request.getParameter("trade_no");
		String trade_status = request.getParameter("trade_status");
		String out_trade_no = request.getParameter("out_trade_no");
		String buyer_id = request.getParameter("buyer_id");

		if (StringUtils.isNotBlank("trade_status") && trade_status.equals("TRADE_SUCCESS")) {
			PayOrderExample example = new PayOrderExample();
			example.createCriteria().andIsPayEqualTo((byte) 0).andOpenIdEqualTo(buyer_id)
					.andTransactionIdEqualTo(trade_no).andOutTradeNoEqualTo(out_trade_no);
			List<PayOrder> selectByExample = payOrderMapper.selectByExample(example);
			if (!selectByExample.isEmpty()) {
				PayOrder payOrder = selectByExample.get(0);
				try {
					manageCaseBoxService.payCaseFinish(payOrder);
				} catch (Exception e) {
					return "";
				}
				return "success";
			} else {
				return "";
			}

		} else {
			return "";
		}
	}

	/**
	 * @author 刘成
	 * @since 2018年9月20日
	 * @param tradeNo
	 * @return
	 * @throws Exception
	 *             押金支付完成处理逻辑
	 */
	@RequestMapping("/payCaseFinish")
	@ResponseBody
	public Map<String, String> payCaseFinish(String tradeNo, String openId) throws Exception {
		Map<String, String> map = new HashMap<>();
		// // 1.修改订单状态为支付
		// PayOrderExample example = new PayOrderExample();
		// example.createCriteria().andTransactionIdEqualTo(tradeNo).andOpenIdEqualTo(openId);
		// List<PayOrder> selectByExample =
		// payOrderMapper.selectByExample(example);
		// if (!selectByExample.isEmpty()) {
		// PayOrder payOrder = selectByExample.get(0);
		// try {
		// manageCaseBoxService.payCaseFinish(payOrder);
		// } catch (Exception e) {
		// map.put("message", "服务器开小差了，请联系管理员处理");
		// }
		// }
		map.put("message", "成功缴纳押金");
		return map;
	}

	/**
	 * @author liuCheng
	 * @since 2018年10月31日 下午6:06:21
	 * @param openId
	 * @return
	 * @throws Exception
	 *             测试人员退款接口
	 */
	@RequestMapping("/refundToTest")
	@ResponseBody
	public Map<String, String> refundToTest(String openId, String trade_no, String refund_amount) throws Exception {
		Map<String, Object> paramMap = new HashMap<>();
		Map<String, String> returnMap = new HashMap<>();
		// 查询押金的订单号和押金金额
		// 缴纳了押金还需要判断是否欠费
		AlipayClient alipayClient = new DefaultAlipayClient(AliConfig.URL, AliConfig.APP_ID, AliConfig.PRIVATE_KEY,
				"json", "UTF-8", AliConfig.ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		paramMap.put("trade_no", trade_no);
		paramMap.put("refund_amount", refund_amount);
		paramMap.put("refund_reason", "测试金额退还");
		String jsonString = JSONObject.toJSONString(paramMap);
		request.setBizContent(jsonString);
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		System.err.println(jsonString);
		System.err.println(response.getBody());
		if (response.isSuccess()) {
			returnMap.put("jumpPage", "0");
			returnMap.put("refundMessage", "申请退款成功");
		} else {
			returnMap.put("jumpPage", "0");
			returnMap.put("refundMessage", "申请退款失败");
		}

		return returnMap;
	}

}
